<template>
  <div class="v2-select">
    <el-select
        :size="size"
        class="w-full"
        ref="select"
        v-model="selectValue"
        v-bind="$attrs"
        @change="change"
    >

      <el-option
          v-for="item in options"
          @click.native="clickOption(item)"
          :key="item.value"
          :label="item.label"
          :value="item.value">
      </el-option>
    </el-select>
  </div>
</template>

<script>
import util from "utils/util";
import http from "network/http";
import ApiResponse from "utils/ApiResponse";

export default {
  name: "v2-select" ,
  props:{
    value: {
      type: [String , Number , Array] ,
      default: ""
    },
    size: 'small',
    config:{
      type: Object ,
      default(){
        return {
          url: '' ,
          method: '',
          options:[],
          map: {} ,
        }
      }
    },

  },
  data(){
    return {
      options: [] ,
      isRequest: false ,
      selectConfig:{} ,
      selectValue: this.value ,
      currentOption: null ,
      list: []
    }
  },
  mounted(){
    this.initSelect() ;
  },
  watch:{
    value(val){
      this.selectValue = val
    },

  },
  methods:{
    clickOption(option){
      this.currentOption = option
    },
    change(val){
      this.$emit('input', val);
      let index = this.$refs.select.hoverIndex
      this.$emit('change', this.list[index]);
    },
    initSelect(){
      let {url , method , options , map , params = {}} = this.config
      let isRequest = !util.isVoid(url) // url不为空就请求网络;
      map = Object.assign({
        disabled: "disabled" ,
        label: 'label' ,
        value: 'value'
      } , map)
      if(isRequest){//url不为空就请求网络;
        this.request(url,util.NVL(method , "get") ,params )
            .then(res=>{
              ApiResponse.init(res)
                  .execute((data)=>{
                    this.list = data
                    this.options = this.selectOptionMap(map , data)
              })
            })
      }else{
        this.list = options
        this.options = this.selectOptionMap(map , options)
      }
    },
    selectOptionMap(map , data){
     return data.map(item=>{
        return {
          label: item[map.label] ,
          value: item[map.value] ,
          disabled: util.NVL(item[map.disabled] , false) ,
        }
      })
    } ,
    request(url , method, data){
      let key = util.is(method.toUpperCase() , "GET")
          .get("params","data")
      let config = {
        url , method ,[key]:data
      }
      return http(config)
    }
  }
}
</script>

<style scoped>
  .v2-select{
    width: 100%;
  }
</style>
